package com.xiangxiangjd.controller;

import cn.afterturn.easypoi.word.WordExportUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xiangxiangjd.bean.Goods;
import com.xiangxiangjd.controller.entity.ApiCode;
import com.xiangxiangjd.controller.entity.Responsible;
import com.xiangxiangjd.controller.helper.$;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.xiangxiangjd.bean.result.ResultPage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xiangxiangjd.service.DateNoService;
import com.xiangxiangjd.bean.DateNo;
import com.xiangxiangjd.controller.model.ApiResultModel;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 添加退役航材的单号 前端控制器
 *
 * @author 肖守凯
 * @since 2021-11-08
 */
@Controller
@RequestMapping("/api/dateNo")
@Api(tags = "退役航材登记")
public class DateNoController extends BaseController {

  /**
   * 添加DateNo
   *
   * @param dateNo 前端传进的参数
   * @return 返回统一信息
   */
  @PostMapping(value = "/addDateNo")
  @ResponseBody
  @PreAuthorize("hasRole('ROLE_USER')")
  @ApiOperation(value = "退役航材登记申请-新增登记（保存/提交）", notes = "退役航材登记申请-新增登记（保存/提交）")
  public ApiResultModel saveDateNo(@RequestBody DateNo dateNo) {

    // 校验是否添加数据
    if (StringUtils.isEmpty(dateNo.getApplicant())) {
      return $.error("请填写申请单位！");
    }
    if (StringUtils.isEmpty(dateNo.getPurchaseDate())) {
      return $.error("请选择获取日期！");
    }
    if (StringUtils.isEmpty(dateNo.getAssetsSource())) {
      return $.error("请填写存放地点！");
    }
    if (dateNo.getGoodsList() == null) {
      return $.error("退役航材最少添加一条！");
    }

    return dateNoService.addDateNo(dateNo);
  }

  /**
   * 分页查询DateNo
   *
   * @param page 页码
   * @param limit 查几条
   * @param dateNo 前端传进的参数
   * @return 返回统一分页信息
   */
  @PostMapping(value = "/findDateNoByPage")
  @ResponseBody
  @PreAuthorize("hasRole('ROLE_USER')")
  @ApiOperation(value = "退役航材登记申请-分页查询", notes = "退役航材登记申请-分页查询")
  public ResultPage findDateNoByPage(Integer page, Integer limit, DateNo dateNo) {
    return dateNoService.findDateNoByPage(page, limit, dateNo);
  }

  /**
   * 编辑DateNo
   *
   * @param dateNo 前端传进的参数
   * @return 返回统一信息
   */
  @PostMapping(value = "admin/editDateNo")
  @ResponseBody
  @PreAuthorize("hasRole('ROLE_USER')")
  @ApiOperation(value = "退役航材登记申请-编辑", notes = "退役航材登记申请-编辑")
  public ApiResultModel editDateNo(DateNo dateNo) {

    return dateNoService.editDateNo(dateNo);
  }

  /**
   * 删除DateNo
   *
   * @param ids 前端传进的ID
   * @return 返回统一信息
   */
  @PostMapping(value = "admin/delDateNo")
  @ResponseBody
  @PreAuthorize("hasRole('ROLE_USER')")
  @ApiOperation(value = "删除", notes = "删除")
  public ApiResultModel delDateNo(@RequestParam("datas") ArrayList ids) {

    List<Goods> list = goodsService.list(new LambdaQueryWrapper<Goods>().in(Goods::getDateNoId, ids));
    if (list.size() > 0) return $.error("请删除 退役航材详细数据");

    return dateNoService.delDateNos(ids);
  }

  /**
   * 查看日期单号的所有航材
   *
   * @param DateNoId 前端传进的参数
   * @return 返回统一信息
   */
  @PostMapping(value = "/showOddAviationMaterials")
  @ResponseBody
  @PreAuthorize("hasRole('ROLE_USER')")
  @ApiOperation(value = "查看日期单号的所有航材", notes = "查看日期单号的所有航材")
  public ResultPage<DateNo> showOddAviationMaterials(Integer DateNoId) {

    DateNo dateNo = dateNoService.selectDateNoByIdDateNo(DateNoId);


    ArrayList<DateNo> list = new ArrayList();
    list.add(dateNo);
    ResultPage data = new ResultPage();
    data.setCount(list.size());
    data.setMsg(ApiCode.success_msg);
    data.setCode(ApiCode.success);
    data.setData(list);
    return data;
  }




  /**
   * 针对 整个 日期单号 进行提交
   * 未提交 改为 待审批
   */

  @ApiOperation(value = "修改日期单号为 待审批", notes = "修改日期单号为 待审批")
  @PostMapping(value = "/setFixedAll")
  @ResponseBody
  @PreAuthorize("hasRole('ROLE_USER')")
  public ApiResultModel setFixedAll(@RequestParam("id") Integer id) {

    boolean update = dateNoService.update(new LambdaUpdateWrapper<DateNo>().set(DateNo::getApprovalState, "1")
            .eq(DateNo::getId, id));
    if (!update) {
      return $.error("提交失败！");
    }

    return $.success("提交成功！");


  }




  /**
   * 审批不通过  可重新提交！
   */
  @PostMapping(value = "/approvalFailed")
  @ResponseBody
  @ApiOperation(value = "审批不通过", notes = "审批不通过", produces = "application/json")
  @PreAuthorize("hasRole('ROLE_ADMIN')")
  public ApiResultModel approvalFailed(String id, String errerReason) {

    boolean update = dateNoService.update(new LambdaUpdateWrapper<DateNo>().set(DateNo::getApprovalState, "3")
            .set(DateNo::getErrerReason, errerReason).eq(DateNo::getId, id));
    if (!update) {
      return $.error("提交失败！");
    }

    return $.success("审批不通过！");
  }




  /**
   * 审批通过
   */
  @ApiOperation(value = "审批通过", notes = "审批通过", produces = "application/json")
  @PostMapping(value = "admin/approved")
  @ResponseBody
  @PreAuthorize("hasRole('ROLE_ADMIN')")
  public ApiResultModel approved(Integer id) {

    return dateNoService.approved(id);
  }







  /**
   * 批量设置固定资产类型
   */
  @PostMapping(value = "/admin/setFixedType")
  @ResponseBody
  @ApiOperation(value = "批量设置资产来源", notes = "批量设置资产来源", produces = "application/json")
  @PreAuthorize("hasRole('ROLE_ADMIN')")
  public ApiResultModel getFixedType(Responsible responsible) {
    boolean update = dateNoService.update(new LambdaUpdateWrapper<DateNo>().set(DateNo::getAssetsSource, responsible.getUpdateContent())
            .in(DateNo::getId, responsible.getIds()));
    if (!update) {
      return $.error("修改失败！");
    }
    return $.success("修改成功！");
  }



  /**
   *
   */
  @GetMapping(value = "/downFileIsNotAuthority")
  @ApiOperation(value = "查看是否有下载权限", notes = "查看是否有下载权限")
  @PreAuthorize("hasRole('ROLE_USER')")
  @ResponseBody
  public ApiResultModel downFileIsNotAuthority(@RequestParam("dateNoId") Integer dateNoId){

    dateNoService.downDocDateNoAllFixed(dateNoId);

    return $.success("开始下载");
  }



  /**
   * 导出doc 单号下的所有商品
   */
  @GetMapping(value = "/downDocDateNoAllFixed")
  @ApiOperation(value = "导出单号所有的商品", notes = "导出单号所有的商品")
//    @PreAuthorize("hasRole('ROLE_USER')")
  public void downDocDateNoAllFixed(@RequestParam("dateNoId") Integer dateNoId) throws Exception {


    Map map=dateNoService.downDocDateNoAllFixed(dateNoId);


    XWPFDocument doc = WordExportUtil.exportWord07("word/SimpleExcel.docx", map);

    doc.enforceReadonlyProtection();

    String fileName = System.currentTimeMillis() + ".docx";
    HttpServletResponse response = getResponse();

    response.reset();
    response.setContentType("application/msword");
    String dispositionValue = "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8");
    response.setHeader("Content-disposition", dispositionValue);
    response.setCharacterEncoding("UTF-8");

    OutputStream output = response.getOutputStream();
    doc.write(output);
    output.close();

  }

}
